package br.com.mtg.movethegarbage.impl;

import android.graphics.RectF;
import android.view.KeyEvent;
import br.com.mtg.movethegarbage.framework.GUIBase;
import br.com.mtg.movethegarbage.framework.Game;
import br.com.mtg.movethegarbage.framework.GameKeyEvent;
import br.com.mtg.movethegarbage.framework.GameTouchEvent;
import br.com.mtg.movethegarbage.framework.Graphics;
import br.com.mtg.movethegarbage.game.Assets;
import br.com.mtg.movethegarbage.graphics.SpriteManager;

public class TextBox extends GUIBase
{
	String textString;
	float fontSize;
	boolean hadFocus;
	int maxLenght;
	Game game;

	public TextBox(int _x, int _y, int _w, int _h)
	{
		super(_x, _y, _w, _h);
		textString = "";
		fontSize = 1.0F;
		maxLenght = -1;
	}

	public TextBox(int _x, int _y, int _w, int _h, float _fontSize, int _maxLenght, Game _game)
	{
		super(_x, _y, _w, _h);
		textString = "";
		fontSize = _fontSize;
		maxLenght = _maxLenght;
		game = _game;
	}

	@Override
	public void draw(Graphics graphics)
	{
		SpriteManager spriteManager = new SpriteManager(graphics, 1);
		spriteManager.beginDraw(Assets.tex_sprites);
		spriteManager.drawSprite(x, y, w, h, Assets.textboxBackground);
		spriteManager.endDraw();
		if (!textString.equals(""))
		{
			Assets.font.setScale(fontSize);
			Assets.font.printAt(textString, x + 5, y + 2);
		}
	}

	@Override
	public void handleEvent(Object event, Game game)
	{
		synchronized (game)
		{
			if (event instanceof GameKeyEvent)
			{
				GameKeyEvent keyEvent = (GameKeyEvent) event;
				if (keyEvent.type == GameKeyEvent.KEY_DOWN)
					return;
				// else
				if (keyEvent.keyCode == KeyEvent.KEYCODE_DEL && !textString.equals(""))
					textString = textString.substring(0, textString.length() - 1);
				else if (keyEvent.keyCode == KeyEvent.KEYCODE_ENTER)
				{
					game.getInput().hideKeyboard(game);
				}
				else if (keyEvent.keyChar != '\0' && (textString.length() < maxLenght || maxLenght == -1))
					textString += keyEvent.keyChar;
			}
			else
			{
				GameTouchEvent touchEvent = (GameTouchEvent) event;
				RectF rect = getRect();
				if (touchEvent.type == GameTouchEvent.TOUCH_DOWN)
				{
					if (rect.contains(touchEvent.touchX, touchEvent.touchY))
					{
						game.getInput().showKeyboard(game);
					}
					else
					{
						game.getInput().hideKeyboard(game);
					}
				}
			}
		}
	}

}
